local MT = minetest
local vMod = vm_lighting_wand

local split = function(s, delimiter)
  local result = {}
  for match in (s .. delimiter):gmatch("(.-)" .. delimiter) do
    match:gsub("%s+", "")
    if match ~= "" then
      table.insert(result, match)
    end
  end
  return result
end

local action_func = {
  set = vMod.set_power,
  add = vMod.add_power,
  remove = vMod.remove_power
}

-- Add a privi to use this command
MT.register_privilege(vMod.modname, {
  description = vMod.locale("Allow player to alter all players stored power (burntime)"),
  give_to_singleplayer = false,
  give_to_admin = false
})

MT.register_chatcommand(vMod.modname, {
  params = "[set|add|remove] [name|me] [amount]",
  description = "performs the given action on the given players name to alter stored power (burntime)",
  privs = {
    vm_lighting_wand = true
  },
  func = function(name, param)
    if not param or param == "" then
      return false, "Error:\nmissing params, please see help"
    end
    local str = split(param, " ")

    -- check and set action if valid
    local action = str[1]
    if not action == "set" or not action == "add" or not action == "remove" then
      return false,
          "[" .. vMod.modname .. "]Error:\nInvalid action\n\tMust be one of \n\t\tset\n\t\tadd\n\t\tremove"
    end

    -- check the player
    local who = str[2]
    local who_name = who
    -- me or self == current player
    if who == "me" or who == "self" then
      who_name = name
    end
    who = MT.get_player_by_name(who_name) or nil
    if not who then
      return false, "[" .. vMod.modname .. "]Error:\n\tUnknown player name - " .. (who_name or "unknown")
    end

    -- check the given amount is valid
    local amount = vMod.round(tonumber(str[3] or 0))
    if not amount or amount <= 0 or amount > vMod.get_max_power() then
      return false, "[" .. vMod.modname .. "]Error:\nInvalid amount given: range = 0 > " .. vMod.get_max_power()
    end

    -- Just pass the amount to the correct function to handle it
    action_func[action](who, amount)
    local power = vMod.get_power(who)
    vMod.logger(name .. " (" .. action .. ") Power for " .. who_name .. " - amount:" .. amount .. " new power:" ..
      power)

    -- Success
    return true,
        "[" .. vMod.modname .. "]Success!\n" .. " amount: " .. amount .. " action: " .. action .. " for: " ..
        who_name .. " new power is now " .. power
  end
})
